<style>
    select[class^="discount-retail-type"]{
        width: 6%;
    }
    td.normal{
        width: 25%
    }
    tr.total{
        background-color: #FFFFCC;
        font-weight: bold;
    }
</style>
<div class="row-fluid">
    <div class="box span12">
        <div class="box-header" data-original-title>
            <h2>
                Order Item(s)
            </h2>
        </div>
        <div class="box-content">
            <?php $pack_price = NULL; ?>
            <?php if ($customer_package): ?>
                <!--Gợi ý Package mà Customer đã mua-->
                <blockquote>
                    This customer have available this package:<br>
                    <strong>Package Name:</strong>
                    <?php echo $customer_package->package->name ?>
                    <br>
                    <strong>Used times:</strong>&nbsp;
                    <span class="label label-info">
                        <?php echo $customer_package->used_times ?></span>
                    <br>
                    <strong>Available:</strong>&nbsp;
                    <span class="label <?php echo $customer_package->available > 0 ? 'label-success' : '' ?>">
                        <?php echo $customer_package->available; ?></span>
                    <br>
                    <br>
                    <?php if (isset($_GET['usePackage'])): ?>
                        <a href="<?php
                        echo Yii::app()->createUrl('order/detail', array(
                            'pk' => $_GET['pk'],
                        ))
                        ?>"
                           class="btn"><i class="icon-undo"></i>&nbsp;Unused this package</a>
                       <?php else: ?>
                        <a href="<?php
                        echo Yii::app()->createUrl('order/detail', array(
                            'pk'         => $_GET['pk'],
                            'usePackage' => $customer_package->package_id
                        ))
                        ?>"
                           class="btn btn-success"><i class="icon-plus"></i>&nbsp;Use this package</a>
                       <?php endif; ?>
                </blockquote>
            <?php endif; ?>

            <form method="POST" onsubmit="return checkOrderForm();">
                <div class="table-responsive">
                    <table class="table table-bordered table-condensed" id="table-order">
                        <thead>
                        <th></th>
                        <th>Item</th>
                        <th>Employee/Commission To</th>
                        <th>Qty</th>
                        <th>Price</th>
                        <th>Discount</th>
                        <th>Tax <?php echo "({$order->tax}%)" ?></th>
                        <th>Hotdeal</th>
                        <th>First Time</th>
                        <th>Final Price</th>
                        </thead>
                        <tbody>
                            <tr>
                                <td>
                                    <a  href="#" >
                                        <img src="<?php echo $order->service->getImageBySize(100, 100); ?>" /> 
                                    </a>
                                </td>
                                <td>
                                    <p class="f-weight"> <?php echo $order->service->s_name ?></p>
                                    <?php echo $order->formartDate() ?><br>
                                    Duration: <?php echo $order->service->duration ?> minutes<br>
                                    Booking: #<?php echo $order->apt_id ?><br>
                                </td>
                                <td>
                                    <div>
                                        <?php foreach ($order->service->staff as $key => $staff): ?>
                                            <?php if ($order->service): ?>
                                                <?php if ($order->service->staff): ?>
                                                    <label for="group_<?php echo $key ?>">
                                                        <input id="group_<?php echo $key ?>" class="checkbox-st"type="checkbox" name="staff[]" value="<?php echo $staff->ukey ?>"
                                                        <?php echo $order->appoint->author->ukey == $staff->ukey ? 'checked="checked"' : '' ?>
                                                               <?php // echo Orders::checkAddedStaff($staff->ukey, $order->order_id) ? 'checked="checked"' : '' ?>>
                                                               <?php echo $staff->name ?>
                                                    </label> <br>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                        <div onclick="$('input[id $=SelectionCheckbox]').attr('checked', this.checked);"></div>
                                    </div>
                                </td>
                                <td>
                                    <input class="voi-order-input" type="text" style="width: 24px;" 
                                           name="qty" value="<?php echo $qty ?>" id="voi-order-qty" />
                                </td>
                                <td>
                                    <?php
                                    //Price của Package đã Add cho Customer
                                    if (isset($_GET['usePackage']) && $customer_package)
                                    {
                                        $pack       = $customer_package->package;
                                        $pack_price = $pack->price / $pack->limit;
//                                    $price = $order->s_price * $qty - $pack_price;
                                    }
//                                else
//                                {
//                                    $price = $order->s_price;
//                                }
                                    ?>
                                    $<?php echo $order->s_price ?>
                                    <input type="hidden" value="<?php echo $order->s_price ?>" id="voi-order-price">
                                </td>
                                <td>
                                    <input class="voi-order-input" type="text" 
                                           value="<?php echo $discount ?>" name="discount"
                                           id="voi-order-discount-value" />
                                    <select class="dr-type voi-order-input" 
                                            id="voi-order-discount-type" name="discount_type">
                                        <option value="%" <?php echo $discount_type == '%' ? 'selected=""' : '' ?> >%</option>
                                        <option value="$" <?php echo $discount_type == '$' ? 'selected=""' : '' ?>>$</option>
                                    </select>

                                    <!--Package Price Discount Text-->
                                    <?php if ($pack_price): ?>
                                        <br><span class="text-success"><b>Package discount:&nbsp;
                                                <?php echo "-$$pack_price" ?></b></span><br>
                                    <?php endif; ?>
                                    <!--End Package Price Discount Text-->    

                                </td>
                                <td>
                                    <span id="voi-order-tax-display">$<?php echo $order->s_price * $order->tax / 100 ?></span>
                                </td>
                                <td><?php echo '$' . $order->getHotdealPrice(); ?></td>
                                <td><?php echo '$' . $order->getFirstTimePrice(); ?></td>
                                <td><span id="voi-order-final">$<?php echo number_format($final, 2) ?></span></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div id="list_retail_product">
                    <div class="row-fluid">
                        <div class="box span12">
                            <div class="box-header" data-original-title>
                                <h2>
                                    Retail Item(s)
                                </h2>
                                <div class="box-icon">
                                    <a class="btn-minimize" href="#"><i class="icon-chevron-down"></i></a>
                                </div>
                            </div>
                            <div class="box-content <?php echo!Yii::app()->user->hasFlash('error') ? 'hide' : ''; ?>">
                                <?php if (Yii::app()->user->hasFlash('error')): ?>
                                    <div class="alert alert-error">
                                        <button type="button" class="close" data-dismiss="alert">×</button>
                                        <?php echo Yii::app()->user->getFlash('error'); ?>
                                    </div>
                                <?php endif; ?>
                                <table class="table table-condensed">
                                    <thead>
                                    <th>Name</th>
                                    <th>Price</th>
                                    <th>Available</th>
                                    <th>Quantity</th>
                                    <th>Total</th>
                                    <th></th>
                                    </thead>
                                    <tbody id="list_retail" class="form-horizontal">
                                        <tr class="total_retail">
                                            <td colspan="6">
                                                <div class="control-group">
                                                    <label class="control-label">Tax <?php echo "({$order->tax}%)" ?></label>
                                                    <div class="controls">
                                                        <input readonly="readonly" name="RetailOrder[tax]" type="text" id="tax_retail" class="voi-order-input ds_item"/>
                                                    </div>
                                                </div>
                                                <div class="control-group">
                                                    <label class="control-label">
                                                        Discount
                                                    </label>
                                                    <div class="controls">
                                                        <input name="RetailOrder[discount]" onkeyup="calcRetailTotal();" type="text" id="discount_retail" class="voi-order-input ds_item"/>
                                                        &nbsp;<select name="RetailOrder[discount_type]" onchange="calcRetailTotal();" class="discount-retail-type voi-order-input">
                                                            <option value="m">$</option>
                                                            <option value="p">%</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="control-group">
                                                    <label class="control-label">Total Retail</label>
                                                    <div class="controls">
                                                        <input type="text" name="RetailOrder[total_price]" id="total_retail_text" readonly="readonly">
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr class="total">
                                            <td colspan="6">
                                                Total: <span id="total_all"></span>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="box-btn">
                    <a class="btn btn-book" id="add_retail_product">
                        <i class="icon-plus"></i>&nbsp;Add retail product</a>
                    <a class="btn btn-success" onclick="showPayment();">
                        <i class="icon-shopping-cart"></i>&nbsp;Checkout</a>
                </div>
                <div class="form-horizontal hide" id="payment-form">	
                    <div class="control-group">                            
                        <label class="control-label" for="amount">Amount</label>
                        <div class="controls">
                            <div class="input-prepend">
                                <span class="add-on">$</span>
                                <input id="amount" name="amount"
                                       value="<?php echo $final ?>" size="16" type="text">
                            </div>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label" for="input2">Method</label>
                        <div class="controls">                                
                            <select id="input2" name="method">
                                <?php foreach (Payment::getListMethod() as $key => $val): ?>
                                    <option value="<?php echo $key ?>"><?php echo $val; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="control-group">
                        <div class="controls">
                            <button class="btn btn-primary">Payment</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    //List retail theo service này
    var PRODUCT_RETAIL = <?php echo Retail::getRetailByService($order->s_id, TRUE) ?>;
    var ID_CLASS = 0;
    $('#add_retail_product').click(function() {
        $('#list_retail_product').css('display', 'block');
        $('#list_retail_product .box-content').css('display', 'block');
        ID_CLASS += 1;
        var _select_retail_product = '';
        _select_retail_product += '<select name="RetailOrderItem[' + ID_CLASS + '][id]" onChange="change_retail_item(' + ID_CLASS + ')" class="l_retail_' + ID_CLASS + '" >';

        PRODUCT_RETAIL.forEach(function(e) {
            _select_retail_product += '<option available="' + e.available + '" value="' + e.id + '" price="' + e.price + '">';
            _select_retail_product += e.name;
            _select_retail_product += '</option>';
        });
        _select_retail_product += '</select>';

        var _html = '';
        _html += '<tr>';
        _html += '<td class="normal">' + _select_retail_product + '</td>';
        _html += '<td class="price_retail_' + ID_CLASS + '">' + '</td>';
        _html += '<td class="available_' + ID_CLASS + '">' + '</td>';
        _html += '<td class="normal">' + '<input name="RetailOrderItem[' + ID_CLASS + '][qty]" type="number" min="1" onchange="change_quanlity($(this))" class="voi-order-input retail-quality" data-id="' + ID_CLASS + '">' + '</td>';
        _html += '<td class="lastest_' + ID_CLASS + '"></td>';
        _html += '<td class="text-center"><button title="Remove" class="btn" onclick="removeRow($(this));">\n\
                                    <i class="icon-remove"></i></button></td>';
        _html += '</tr>';

        $('.total_retail').before(_html);
        change_retail_item(ID_CLASS);
    });
    function calcRetailTotal()
    {
        var total = 0;
        $('[class^="lastest_"]').each(function() {
            var each_price = parseFloat($(this).text().replace(/[^\d.]/g, ''));
            total += each_price;
        });
        var tax_value = total * <?php echo $order->tax ?> / 100;
        //Ghi tax value
        $('#tax_retail').val('$' + tax_value.formatMoney(2, '.', ','));

        //Trừ discount
        discount_retail = $('#discount_retail').val() ? $('#discount_retail').val() : 0;
        if ($('.discount-retail-type').val() != 'm') {
            discount_retail = total * discount_retail / 100;
        }
        total = total - discount_retail + tax_value;
        var total_sv = parseFloat($('#voi-order-final').text().replace(/[^\d.]/g, ''));
        total_all = total_sv + total;
        $('#total_retail_text').val('$' + total.formatMoney(2, '.', ','));
        $('#total_all').text('$' + total_all.formatMoney(2, '.', ','));
        $('#amount').val(total_all.formatMoney(2, '.', ','));
    }

    //khi thay doi so luong
    function change_quanlity(e) {
        cal_retail(e);
        calcRetailTotal();
    }

    function change_retail_item(e) {
        //lay gia
        var price = $('.l_retail_' + e + ' option:selected').attr('price');
        $('.price_retail_' + e).text('$' + price);
        //lay available
        var available = $('.l_retail_' + e + ' option:selected').attr('available');
        $('.available_' + e).text(available);
    }

    function change_price(e) {
        var data_id = e.attr('data-id');

        var element = $('.retail-quality[data-id="' + data_id + '"]');
        cal_retail(element);
    }

    function cal_retail(e) {
        //so vong lap
        var stt = e.attr('data-id');
        //set price
        var price = $('.l_retail_' + stt + ' option:selected').attr('price');
        //get quanlity
        var quanlity = e.val();
        var latest_money = price * quanlity;
        //tinh thue
        //                                            latest_money = latest_money + (latest_money * 0.07) / 100;
        $('.lastest_' + stt).text('$' + latest_money.formatMoney(2, '.', ','));
        calcRetailTotal();
    }
    function showPayment()
    {
        $('#payment-form').show();
        $('#btn-check-out').hide();
        $('.voi-order-input').each(function() {
            $('.voi-order-input').attr('readonly', 'true');
        });
        $('.checkbox-st').css('pointer-events', 'none');
        $('#voi-order-discount-type').css('pointer-events', 'none');
        $('#add_retail_product').hide();
    }

    function checkOrderForm()
    {
        iqty = $('#voi-order-qty');
        qty = parseInt(iqty.val());

        if (qty === 0)
        {
            alert('Qty must larger than 0');
            iqty.focus();
            return false;
        }
        return true;
    }
    function removeRow(el)
    {
        el.parent().parent().html('');
        calcRetailTotal();
    }

    $(function() {
        $('.voi-order-input').keyup(function() {
            calculate_order();
        });
        $('select.voi-order-input').change(function() {
            calculate_order();
        });

        function calculate_order()
        {
            price = <?php echo $order->s_price ?>;//Service price
            qty = parseInt($('#voi-order-qty').val());//Service qty
            idiscount = $('#voi-order-discount-value');
            discount = idiscount.val() ? parseFloat(idiscount.val()) : 0;//Nếu không có mặc định là 0
            idiscount_type = $('#voi-order-discount-type');
            discount_type = idiscount_type.val();//Discount type % hoặc $

            subtotal = (price * qty);
            if (discount_type === '%')
            {
                discount = (subtotal * discount) / 100;
            }
<?php if ($pack_price): ?>
                discount +=<?php echo $pack_price ?>;
<?php endif; ?>
            tax_value = subtotal * <?php echo $order->tax ?> / 100;
            //Append tax value by new total
            $('#voi-order-tax-display').text("$" + tax_value.formatMoney(2, '.', ','));
            final = subtotal - discount + tax_value;
            final = final < 0 ? 0 : final;
            $('#voi-order-final').html("$" + final.formatMoney(2, '.', ','));//Total vào row Final Price
            //Tổng retail và service
            //Check nếu có add retail
            var total_retail = 0;
            $('[class^="lastest_"]').each(function() {
                var each_price = parseFloat($(this).text().replace(/[^\d.]/g, ''));
                total_retail += each_price;
            });
            var total_all;
            if (total_retail > 0)
            {
                total_all = parseFloat($('#total_all').text().replace(/[^\d.]/g, ''));
                $('#amount').val(total_all.formatMoney(2, '.', ','));
            }
            else {
                $('#amount').val(final.formatMoney(2, '.', ','));
            }
        }
    });
    //Ext format price
    Number.prototype.formatMoney = function(c, d, t) {
        var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
        return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
    };
</script>
